package com.semidata.trp.report.http;

import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.QueryStringDecoder;

import com.semidata.rtd.core.http.server.AbstractDispatchHandler;
import com.semidata.rtd.core.http.server.HttpSession;
import com.semidata.rtd.core.log.Logger;
import com.semidata.trp.report.report.NRTRecompute;
import com.semidata.trp.report.report.SortLogs;

public class NRTRecomputeHandler extends AbstractDispatchHandler {

	public NRTRecomputeHandler(ChannelHandlerContext ctx, HttpRequest request) {
		super(ctx, request);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void handle(HttpSession session) {
		// TODO Auto-generated method stub
		HttpRequest request = session.getRequest();
		String requestUri = request.getUri();
		QueryStringDecoder decoder = new QueryStringDecoder(requestUri);
		final Map<String, List<String>> results = decoder.parameters();
		if (results.get("d") == null) {
			session.getResponse().error(HttpResponseStatus.BAD_REQUEST);
		} else {
			Thread thread = new Thread(new Runnable() {
				public void run() {
					//NRTRecompute nrtReport = new NRTRecompute();
					SortLogs nrtReport = new SortLogs();
					final String date = results.get("d").get(0);
					boolean ignore = false;
					if (results.get("i") != null) {
						ignore = Boolean.valueOf(results.get("i").get(0));
					}
					try {
						nrtReport.setFileList(date, ignore);
					} catch (Exception e) {
						Logger.log("ERROR", date);
						Logger.log("ERROR", e.getMessage());
					}
					nrtReport = null;
				}
			});
			thread.start();
			session.getResponse().end("start");
			try {
				thread.join();
				Logger.log("DEBUG", "recompute finished !");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
